/*
*	日期选择插件
*/

;(function (jQuery) {
	'use strict';

	var Calendar = function (target, options) {
		var self = this;
		self.target = target;
		self.options = options;
		self.element = $($.fn.calendar.template.whole);

		//  设置位置
		switch (self.options.position) {
			case 'top':
				var top = self.target[0].offsetTop - self.options.height,
					left = self.target[0].offsetLeft;
				break;
			case 'right':
				var top = self.target[0].offsetTop,
					left = self.target[0].offsetLeft + self.target[0].offsetWidth;
				break;
			case 'bottom':
				var top = self.target[0].offsetTop + self.target[0].offsetHeight,
					left = self.target[0].offsetLeft;
				break;
			case 'left':
				var top = self.target[0].offsetTop,
					left = self.target[0].offsetLeft - self.options.width;
				break;
			default:
				var top = self.target[0].offsetTop + self.target[0].offsetHeight,
					left = self.target[0].offsetLeft;
				break;
		}

		if (! $(document.body).find('.calendar')[0]) {
			$(document.body).append(
				self.element.css({
					'top': top,
					'left': left,					
				})
			);
		}

		//  添加主题
		if (self.options.theme) {
			self.element.addClass(self.options.theme);
		}
		//  动画效果
		if (self.options.transition) {
			self.element.addClass(self.options.transition);
		} 

		//  initialization
		self.display = false;
		self.init();
		self.show();
		return self;
	};

	Calendar.prototype = {
		constructor: Calendar,

		//  显示
		show: function () {
			var self = this,
				e = $.Event('show.calendar');
			if (self.display) {
				return;
			}
			self.element.trigger(e).css('display', 'block');
			if (self.options.transition) {
				//  force reflow
				self.element[0].offsetWidth;
				self.element.addClass('in');
			}
			self.display = true;
			return self;
		},

		//  隐藏
		hide: function () {
			var self = this,
				e = $.Event('hide.calendar');
			if (self.options.transition) {
				//  动画结束
				self.element.one('transitionend, webkitTransitionEnd', function () {
					self.element.removeClass('out').css('display', 'none');
					self.display = false;
					self.destory();
				});
				self.element.trigger(e).removeClass('in').addClass('out');
				//  force reflow
				self.element[0].offsetWidth;
			}
			else {
				self.element.trigger(e).css('display', 'none');	
				self.display = false;
				self.destory();
			}
			return self;
		},

		//  移除
		destory: function () {
			var self = this;
			if (! self.display) {
				self.element.off('.calendar').remove();
				self = null;
			}
			else {
				self.hide();
			}
		},

		//  初始化日历
		init: function () {
			var self = this,
				date = new Date(),
				year = date.getFullYear(),
				month = date.getMonth(),
				cur_year = year,
				cur_month = month,
				cur_day = date.getDate();

			//  默认显示本月日期
			set_date();

			//  月份切换
			switch_month();
			
			//  年份切换
			switch_year();

			//  设置日期
			function set_date() {
				var	first_day_week = new Date(year, month, 1).getDay(),
					month_days = calculate_days(year, month), 
					prev_month_days = calculate_days(year, month - 1),
					data = [];

				self.element.find('.calendar-body tr:gt(0)').empty();

				//  跨年
				if (month < 0) {
					month = 11; 
					year --;
				}
				if (month > 11) {
					month = 0; 
					year ++;
				}

				//  添加日期格子
				for (let i = 1; i < 7; i ++) {
					self.element.find('.calendar-body tr').eq(i)
						.append('<td></td><td></td><td></td><td></td><td></td><td></td><td></td>');
				}

				self.date_box = self.element.find('.calendar-body td');

				//  年、月显示
				self.element.find('.calendar-year span').text(year + '年');
				self.element.find('.calendar-month').text((month + 1) + '月');

				//  上个月日期
				if (first_day_week === 0) {
					first_day_week = 7;
				}
				for (let i = first_day_week - 1; i >= 0; i --) {
					data.push('<span>' + (prev_month_days - i) + '</span>');
				}

				//  本月日期
				for (let i = 1; i <= month_days; i ++) {
					//  今天
					if (cur_day === i && month === cur_month && year === cur_year) {
						self.date_box.eq(data.length).addClass('today');
					}
					data.push(i);
				}

				//  下月日期
				var next_month_days = self.date_box.length - data.length;
				for (let i = 1; i <= next_month_days; i ++) {
					data.push('<span>' + i + '</span>');
				}

				//  添加日期
				$.each(data, function (index, value) {
					self.date_box.eq(index)
						.html(value)
						.on('click.calendar', function (e) {
							e.preventDefault();
							var $this = $(this);
							//  点击上月日期切换到上一月
							if (index < first_day_week) {
								month --;
								set_date();
							}
							//  点击下月日期切换到下一月
							else if (index > month_days + first_day_week - 1) {
								month ++;
								set_date();
							}
							//  获取选择的日期值
							else {
								self.target.val(year + self.options.join + (month + 1) + self.options.join + $this.text());
								self.hide();
							}
						});
				});
			}

			//  计算月份中的天数
			function calculate_days(year, month) {
				var month_days_arr = [31,28,31,30,31,30,31,31,30,31,30,31];
				if (month < 0) {
					month = 11;
				}
				if (month > 11) {
					month = 0;
				}

				if (month === 1) {
					return ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) ? 29 : 28;
				}
				else {
					return month_days_arr[month];
				}
			}

			//  月份切换
			function switch_month() {
				//  上一月
				self.element.on('click.calendar', '[data-calendar="month-prev-btn"]', function (e) {
					e.preventDefault();
					month --;
					set_date();
				});
				//  下一月
				self.element.on('click.calendar', '[data-calendar="month-next-btn"]', function (e) {
					e.preventDefault();
					month ++;
					set_date();
				});
			}

			//  年份切换
			function switch_year() {
				//  上一年
				self.element.on('click.calendar', '[data-calendar="year-prev-btn"]', function (e) {
					e.preventDefault();
					if (year > 1900) {
						year --;
					}
					set_date();
				});
				//  下一年
				self.element.on('click.calendar', '[data-calendar="year-next-btn"]', function (e) {
					e.preventDefault();
					if (year < 2090) {
						year ++;
					}
					set_date();
				});
			}
		},
	};

	//  调用执行  
	$.fn.calendar = function (options) {
		options = $.extend({}, $.fn.calendar.defaults, options);
		var target = this;
		this.on('click', function (e) {
			e.preventDefault();
			var calendar = new Calendar(target, options);
		});
		return this;
	};

	//  模板
	$.fn.calendar.template = {
		whole: '<div class="calendar">' +
			   '<div class="calendar-head">' +
			   '<a href="javascript:;" class="calendar-month-prev" data-calendar="month-prev-btn"><<</a>' +
			   '<div class="calendar-year">' +
			   '<span>year</span>' + 
			   '<a href="javascript:;" class="calendar-year-prev" data-calendar="year-prev-btn">-</a>' +
			   '<a href="javascript:;" class="calendar-year-next" data-calendar="year-next-btn">+</a>' +
			   '</div>' +
			   '<div class="calendar-month">month</div>' +
			   '<a href="javascript:;" class="calendar-month-next" data-calendar="month-next-btn">>></a>' +
			   '</div>' +	
			   '<table class="calendar-body">' + 
			   '<tr class="calendar-week">' + 
			   '<th class="reset">日</th>' +
			   '<th>一</th>' +
			   '<th>二</th>' +
			   '<th>三</th>' +
			   '<th>四</th>' +
			   '<th>五</th>' +
			   '<th class="reset">六</th>' +
			   '</tr>' + 
			   '<tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr>' +
			   '</table>' +
			   '</div>',
	};

	//  默认参数
	$.fn.calendar.defaults = {
		theme: '',
		join: '-',
		transition: 'fade',
		position: 'bottom',
	};
	
}($));